import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import vuexPersist from "vuex-persist";

export default new Vuex.Store({
  state: {
    user: "", //用户名
    list: [], //列表数据
    name: "",
    age: "",
    city: "",
    //添加的input双向数据绑定的内容

    flag: false,
    //true 代表编辑 false 代表添加

    editIndex: -1,
    //编辑的数据的下标

    lock: false,
    //控制锁定的状态
  },
  mutations: {
    setuser(state, val) {
      state.user = val;
    },
    //保存用户名
    exit(state) {
      state.user = "";
    },
    //把用户名清空

    add(state) {
      state.list.push({ name: state.name, age: state.age, city: state.city });
      state.name = "";
      state.age = "";
      state.city = "";
    },
    //添加

    edit(state, index) {
      state.editIndex = index;
      //保存修改的下标

      state.name = state.list[index].name;
      state.age = state.list[index].age;
      state.city = state.list[index].city;
    },

    update(state) {
      state.list[state.editIndex].name = state.name;
      state.list[state.editIndex].age = state.age;
      state.list[state.editIndex].city = state.city;
      state.name = "";
      state.age = "";
      state.city = "";
      state.flag = false;
      //修改完成后 把状态变为添加的状态
    },
  },
  actions: {},
  modules: {},
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
});
